package com.voice.call.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import voice.voice.call.cache.ConfigSystemCache;

import com.voice.call.common.Const;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.LuckyCredit;
import com.voice.call.entity.AdvertOperateLog;
import com.voice.call.entity.LuckyCreditStar;
import com.voice.call.entity.LuckyCreditUser;
import com.voice.call.mapper.LuckyCreditMapper;
import com.voice.call.service.ConsumeLogService;
import com.voice.call.service.AdvertOperateLogService;
import com.voice.call.service.LuckyCreditService;
import com.voice.call.service.LuckyCreditStarService;
import com.voice.call.service.LuckyCreditUserService;
import com.voice.call.service.SupportMccService;
import com.voice.call.service.UserAccountService;
import com.voice.call.utils.StringUtil;

@Service
public class LuckyCreditServiceImpl implements LuckyCreditService{
	
	private final Logger log = LoggerFactory.getLogger(LuckyCreditServiceImpl.class);
	
	@Resource
	private ConsumeLogService consumeLogService;
	
	@Resource
	private ConfigSystemCache configSystemCache;
	
	@Resource
	private AdvertOperateLogService luckyCreditPlayService;
	
	@Resource
	private LuckyCreditUserService luckyCreditUserService; 
	
	@Resource
	private LuckyCreditStarService luckyCreditStarService;
	
	@Resource
	private LuckyCreditMapper luckyCreditMapper;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private SupportMccService supportMccService;

	@Override
	public Result getLuckyCreditList(Integer user_id){
		
		try {
			
			
			int star_num = 2;
			LuckyCreditUser luckyCreditUser = luckyCreditUserService.getLuckyCreditUserForId(user_id);
			if (luckyCreditUser!=null) {
				star_num = luckyCreditUser.getStarNum().intValue();
			}
			
			//删除上一次玩的记录
			//luckyCreditPlayService.deleteLuckyCreditPlay(user_id,Const.TASK_LUCKY_CREDIT);
			
			int total = consumeLogService.getLuckyCreditPlayTotal(user_id);
			int limit_total =Integer.valueOf(configSystemCache.get(Const.LUCKY_CREDIT_LIMIT));
			int total_integral = consumeLogService.getTodayIntegral(user_id);
			Map<String, Object> rsMap = new HashMap<String, Object>();
			rsMap.put("star_num", star_num);//显示心数量
			rsMap.put("today_integral", total_integral);//获取今天最大积分
			rsMap.put("play_total", total);//已玩次数
			rsMap.put("limit_total", limit_total);//最大可玩次数
			rsMap.put("left_total", limit_total - total);//剩余可玩次数
			
			return new Result(rsMap);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(ResultEnum.FAILED);
		}
		
	}
	
	@Override
	public Result playLuckyCredit(Integer user_id,boolean hasAdvert){
		
		if (consumeLogService.hasOverMaxIntegralLimit(user_id)) {
			log.info("超过当日获取积分最大限制");
			return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
		}
		
		//判断是否超过最大限制玩的次数
		int total = consumeLogService.getLuckyCreditPlayTotal(user_id); //获取今天玩的次数
		String maxStr = configSystemCache.get(Const.LUCKY_CREDIT_LIMIT);
		if (StringUtil.isEmpty(maxStr)) {
			log.error("未配置当日获取积分最大限制");
		}else {
			Integer limit_total =Integer.valueOf(maxStr);
			if(total>=limit_total.intValue()){
				log.info("lucky credit 超过最大可玩次数");
				return new Result(ResultEnum.LUCKY_CREDIT_LIMIT);
			}
		}
		
		//生成随机中奖数
		
		Map<String, Integer> integralMap = null;
		if (hasAdvert) { //有广告
			int winNum = (int)(1+Math.random()*(100-1+1)); //从1到10的int型随数
			log.info("用户id={},中奖数字为={}",user_id,winNum);
			integralMap = this.getMapLuckyCreditWinIntegral(user_id,winNum);
			if (integralMap == null) {
				return new Result(ResultEnum.SYSTEM_ERROR);
			}
		}else { //无广告
			log.info("无广告，积分为0");
		}
		
		AdvertOperateLog play = luckyCreditPlayService.addMapLuckyCreditPlay(Const.TASK_LUCKY_CREDIT,user_id, integralMap);
		
		if (play ==null) {
			return new Result(ResultEnum.FAILED);
		}
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("id", play.getId());
		rsMap.put("integral",play.getIntegral());
		return new Result(rsMap);
		
		
	}
	
	//获取中奖积分
	private Map<String, Integer> getMapLuckyCreditWinIntegral(Integer user_id,int winNum) {
		
		//获取额外积分
		Integer extraIngetral = luckyCreditUserService.getExtraLuckyCreditIntegral(user_id);
		if (extraIngetral == null) {
			extraIngetral = 0;
		}
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("status", Const.Y);
		List<LuckyCredit> list = luckyCreditMapper.list(rsMap);
		if (list!=null && !list.isEmpty()) {
			
			Integer prevMin = null; //前一个最小值
			Integer prevMax = null; //前一个最大值
			for (LuckyCredit luckyCredit : list) {
				
				if (prevMin == null) { //第一次
					prevMin = Integer.valueOf(1);
					prevMax = luckyCredit.getRate();
				}else {
					prevMin = prevMax + 1;
					prevMax = luckyCredit.getRate() + prevMin -1;
				}
				log.info("integral={},中奖范围,from={},to={}",luckyCredit.getIntegral(),prevMin,prevMax);
				if (prevMin.intValue() <= winNum && winNum <= prevMax.intValue()) {
					log.info("中奖啦!");
					Map<String, Integer> intMap = new HashMap<String, Integer>();
					intMap.put("total", luckyCredit.getIntegral() + extraIngetral);
					intMap.put("lucky_integral", luckyCredit.getIntegral());
					intMap.put("star_integral", extraIngetral);
					intMap.put("rand_num", winNum);
					return intMap;
				}
			}
			
		}
		return null;
	}
	
	//获取中奖积分
	private Integer getLuckyCreditWinIntegral(Integer user_id,int winNum) {
		
		//获取额外积分
		Integer extraIngetral = luckyCreditUserService.getExtraLuckyCreditIntegral(user_id);
		if (extraIngetral == null) {
			extraIngetral = 0;
		}
		
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("status", Const.Y);
		List<LuckyCredit> list = luckyCreditMapper.list(rsMap);
		if (list!=null && !list.isEmpty()) {
			
			Integer prevMin = null; //前一个最小值
			Integer prevMax = null; //前一个最大值
			for (LuckyCredit luckyCredit : list) {
				
				if (prevMin == null) { //第一次
					prevMin = Integer.valueOf(1);
					prevMax = luckyCredit.getRate();
				}else {
					prevMin = prevMax + 1;
					prevMax = luckyCredit.getRate() + prevMin -1;
				}
				log.info("integral={},中奖范围,from={},to={}",luckyCredit.getIntegral(),prevMin,prevMax);
				if (prevMin.intValue() <= winNum && winNum <= prevMax.intValue()) {
					log.info("中奖啦!");
					return luckyCredit.getIntegral() + extraIngetral;
				}
			}
			
		}
		return null;
		
	}
	
	//老虎机积分兑换
	@Override
	public	Result luckyCreditExchange(Integer id,Integer view_ad_time,String ip){
		
		if(!supportMccService.isSupportCountry(ip)){
			log.info("不支持注册国家，老虎机积分兑换");
			return new Result(ResultEnum.ILLEGAL_INTERVAL_ERROR);
		}
	
		AdvertOperateLog play=luckyCreditPlayService.getLuckyCreditPlayForId(id);
		if (play == null) { //非法兑换id
			return new Result(ResultEnum.LUCKY_CREDIT_EXCHANGE_ILLEGAL);
		}
		if (consumeLogService.hasOverMaxIntegralLimit(play.getUserId())) {
			log.info("超过当日获取积分最大限制");
			return new Result(ResultEnum.INTEGRAL_LIMIT_ERROR);
		}
		
		if (play.getStatus().equals(Const.N)) {
			log.info("当前积分已兑换");
			return new Result(ResultEnum.TASK_EXCHANGE_ERROR);
		}
		
		if (play.getIntegral().equals(0)) { //不加积分
			
			//修改状态
			luckyCreditPlayService.updateStatus(play.getId(), Const.N,view_ad_time);
			return new Result();
			
		}else { //加积分
			
			//1.帐户添加积分,添加记录
			if(userAccountService.updateAccountBlance(play.getUserId(), play.getIntegral(), true)){
				log.info("用户新增积分成功");
				consumeLogService.addConsumeLog(play.getUserId(), Const.TASK_LUCKY_CREDIT, Const.TASK_LUCKY_CREDIT,play.getIntegral(),true, null);
				//2.修改老虎机积分兑换状态
				luckyCreditPlayService.updateStatus(play.getId(), Const.N,view_ad_time);
				//3.修改心数量
				LuckyCreditStar luckyCreditStar=luckyCreditStarService.getLuckyCreditStarForAdTime(view_ad_time);
				if (luckyCreditStar!=null) {
					luckyCreditUserService.updateStarNum(play.getUserId(), luckyCreditStar.getStarNum());
				}
				return new Result();
				
			}else {
				log.error("用户新增积分失败");
				return new Result(ResultEnum.FAILED);
			}
		}
		
		
		
		
	}
}
